// --------------------------------------------------------------------------------------------------------------------
// <copyright file="Primes.cs" company="JDML Consulting Ltd.">
//   Copyright 2011 Photon Project - http://photon.codeplex.com
// </copyright>
// <summary>
//   Prime number generation.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace Photon
{
    /// <summary>
    /// Prime number generation.
    /// </summary>
    internal static class Primes
    {
        /// <summary>
        /// Gets the next prime number after <paramref name="value"/>.
        /// </summary>
        /// <param name="value">The value.</param>
        /// <returns>The next prime number after <see cref="value"/>.</returns>
        public static int NextPrime(int value)
        {
            // 2 is the only even prime
            if (value == 2)
            {
                return value;
            }

            // Next odd number
            value += (value & 1) ^ 1;

            while (true)
            {
                var div = 3;
                while (true)
                {
                    if (div * div > value)
                    {
                        return value;
                    }
                    
                    if (value % div == 0)
                    {
                        break;
                    }
                    
                    div += 2;
                }

                value += 2;
            }
        }
    }
}